package com.app.ytong.jpush;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;


import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import cn.jpush.android.api.CmdMessage;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;
import my.IntentUtils;
import my.LogUtil;
import my.SystemParamsUtils;

/**
 *
 */
public class JpushReceiver extends JPushMessageReceiver {
    private static final String TAG = "JpushReceiver";

    @Override
    public void onMessage(Context context, CustomMessage customMessage) {
        Log.e(TAG, "[onMessage] " + customMessage);
        processCustomMessage(context, customMessage);
    }

    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageOpened] " + message);
        try {
            String extr = message.notificationExtras;
            LogUtil.i(TAG,"[MyReceiver] 用户点击打开了通知---onNotifyMessageOpened-->" + extr);
            if (!TextUtils.isEmpty(extr)) {
//                JpushMessageBean beanJ = com.alibaba.fastjson.JSONObject.parseObject(extr, JpushMessageBean.class);
//                if (beanJ.getDeviceType()) {
//                    Bundle ex = new Bundle();
//                    ex.putSerializable("data", msgListData);
//                    Intent intentTo = new Intent(context, PushMidActivity.class);
//                    intentTo.putExtras(ex);
//                    intentTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//                    context.startActivity(intentTo);
//                } else {
//                    openApp(context);
//                }
                openApp(context);
            } else {
                openApp(context);
            }

        } catch (Throwable throwable) {

        }
    }

    @Override
    public void onMultiActionClicked(Context context, Intent intent) {
        Log.e(TAG, "[onMultiActionClicked] 用户点击了通知栏按钮");
        String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA);


        //开发者根据不同 Action 携带的 extra 字段来分配不同的动作。
        if (nActionExtra == null) {
            Log.d(TAG, "ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null");
            return;
        }

        Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");

        Bundle bundle = intent.getExtras();
        Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        //打开自定义的Activity
//				Intent i = new Intent(context, HomeTabActivity.class);
//				i.putExtras(bundle);
//				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//				context.startActivity(i);
        String extr = bundle.getString(JPushInterface.EXTRA_EXTRA);
        LogUtil.i("[MyReceiver] 用户点击打开了通知----->" + extr);
//        if (!TextUtils.isEmpty(extr)) {
//            JpushMessageBean beanJ = com.alibaba.fastjson.JSONObject.parseObject(extr, JpushMessageBean.class);
//            UserMsgListData msgListData = beanJ.getMsgListData();
//            if (msgListData.isShowDetail()) {
//                Bundle ex = new Bundle();
//                ex.putSerializable("data", msgListData);
//                Intent intentTo = new Intent(context,PushMidActivity.class);
//                intentTo.putExtras(ex);
//                intentTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//                context.startActivity(intentTo);
////                ActivityTool.skipActivity(context, PushMidActivity.class, ex);
//            } else {
//                openApp(context);
//            }
//        } else {
//            openApp(context);
//        }


        if (nActionExtra.equals("my_extra1")) {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮一");
        } else if (nActionExtra.equals("my_extra2")) {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮二");
        } else if (nActionExtra.equals("my_extra3")) {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮三");
        } else {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮未定义");
        }
    }

    @Override
    public void onNotifyMessageArrived(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageArrived] " + message);
    }

    @Override
    public void onNotifyMessageDismiss(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageDismiss] " + message);
    }

    @Override
    public void onRegister(Context context, String registrationId) {
        Log.e(TAG, "[onRegister] " + registrationId);
    }

    @Override
    public void onConnected(Context context, boolean isConnected) {
        Log.e(TAG, "[onConnected] " + isConnected);
    }

    @Override
    public void onCommandResult(Context context, CmdMessage cmdMessage) {
        Log.e(TAG, "[onCommandResult] " + cmdMessage);
    }

    @Override
    public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onTagOperatorResult(context, jPushMessage);
        super.onTagOperatorResult(context, jPushMessage);
    }

    @Override
    public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context, jPushMessage);
        super.onCheckTagOperatorResult(context, jPushMessage);
    }

    @Override
    public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context, jPushMessage);
        super.onAliasOperatorResult(context, jPushMessage);
    }

    @Override
    public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
//		TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context,jPushMessage);
        super.onMobileNumberOperatorResult(context, jPushMessage);
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, CustomMessage customMessage) {
        String extr = customMessage.extra;
        try {
            JpushMessageBean beanJ = com.alibaba.fastjson.JSONObject.parseObject(extr, JpushMessageBean.class);

//            if(beanJ.getMsgType().equals(MessageListData.MSG_TYPE_NOTICE)){//有新的公告
//                EventBus.getDefault().post(new HomeIndexActivity.EventHomeIndex(0));
//            }
//            EventBus.getDefault().post(new HomeIndexActivity.EventHomeIndex(0));
            SystemParamsUtils.SetLauncherIconNum(context,beanJ.getUnReadCount());
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.i("processCustomMessage-->json解析错误");
        }

    }


    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Logger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }



    void openApp(Context context) {
        LogUtil.i(TAG,"打开应用了---------》");
        //打开自定义的Activity
//		Intent i = new Intent(context, HomeTabActivity.class);
//		i.putExtras(bundle);
//		//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//		context.startActivity(i);

        if (!IntentUtils.isAppOnForeground(context)) {
            IntentUtils.openAppByPacagename(context, "com.ffapp.firrescue");
        }
    }

}
